JRoutes = CreateFrame("Frame", "JRoutes", nil)

-- Just to make sure it's always 'seen' (there's nothing that can be seen, but still...), and therefore always updating.
JRoutes:SetFrameStrata("TOOLTIP")

JRoutes.tooltip = CreateFrame("GameTooltip", "JRoutesTooltip", nil, "GameTooltipTemplate")
JRoutes.objective_objects = {}
JRoutes.user_objectives = {}
JRoutes.quest_objects = {}
JRoutes.player_level = 1
JRoutes.locale = GetLocal()

JRoutes.faction = (UnitFactionGroup("player") == "Alliance" and 1) or
                      (UnitFactionGroup("player") == "Horde" and 2)

JRoutes.route = {}
JRoutes.to_add = {}
JRoutes.to_remove = {}
JRoutes.quest_log = {}
JRoutes.pos = {nil, {}, 0, 0, 1, "You are here.", 0}
JRoutes.sharing = false -- Will be set to true when sharing with at least one user.

function JRoutes:Initialize()
  
  if JRoutes_IsPolluted(_G) then
    self:TextOut("xx")
    self:Purge(nil, true, true)
  end
  
  local signature = expected_version .. " on " .. GetBuildInfo()
  JRoutes_Quests[signature] = JRoutes_Quests[signature] or {}
  JRoutes_Objectives[signature] = JRoutes_Objectives[signature] or {}
  JRoutes_FlightInstructors[signature] = JRoutes_FlightInstructors[signature] or {}
  JRoutes_FlightRoutes[signature] = JRoutes_FlightRoutes[signature] or {}
  
  JRoutes_Quests_Local = JRoutes_Quests[signature]
  JRoutes_Objectives_Local = JRoutes_Objectives[signature]
  JRoutes_FlightInstructors_Local = JRoutes_FlightInstructors[signature]
  JRoutes_FlightRoutes_Local = JRoutes_FlightRoutes[signature]
  
  JRoutes_SeenRealms[GetRealmName()] = true -- some attempt at tracking private servers
  
  self.player_level = UnitLevel("player")

  self:UnregisterEvent("VARIABLES_LOADED")
  self:RegisterEvent("PLAYER_TARGET_CHANGED")
  self:RegisterEvent("LOOT_OPENED")
  self:RegisterEvent("QUEST_COMPLETE")
  self:RegisterEvent("QUEST_LOG_UPDATE")
  self:RegisterEvent("QUEST_PROGRESS")
  self:RegisterEvent("MERCHANT_SHOW")
  self:RegisterEvent("QUEST_DETAIL")
  self:RegisterEvent("TAXIMAP_OPENED")
  self:RegisterEvent("PLAYER_CONTROL_GAINED")
  self:RegisterEvent("PLAYER_LEVEL_UP")
  self:RegisterEvent("PARTY_MEMBERS_CHANGED")
  self:RegisterEvent("CHAT_MSG_ADDON")
  self:RegisterEvent("CHAT_MSG_SYSTEM")
  self:RegisterEvent("BAG_UPDATE")
  self:RegisterEvent("GOSSIP_SHOW")

  for key, def in pairs(JRoutes_DefaultPref) do
    if JRoutes_Pref[key] == nil then
      JRoutes_Pref[key] = def
    end
  end

  self:SetLocaleFonts()

  if JRoutes_Pref.share and not JRoutes_Pref.solo then
    self:EnableSharing()
  end

  if JRoutes_Pref.hide then
    self.map_overlay:Hide()
  end

  self:HandlePartyChange()

  self:Nag("all")

  for locale in pairs(JRoutes_StaticData) do
    if locale ~= self.locale then
      -- Will delete references to locales you don't use.
      JRoutes_StaticData[locale] = nil
      _G["JRoutes_StaticData_" .. locale] = nil
    end
  end

  local static = JRoutes_StaticData[self.locale]

  if static then
    if static.flight_instructors then for faction in pairs(static.flight_instructors) do
      if faction ~= self.faction then
        -- Will delete references to flight instructors that don't belong to your faction.
        static.flight_instructors[faction] = nil
      end
    end end

    if static.quest then for faction in pairs(static.quest) do
      if faction ~= self.faction then
        -- Will delete references to quests that don't belong to your faction.
        static.quest[faction] = nil
      end
    end end
  
    if not JRoutes:IsWrath() then
      for cat, list in pairs(static.objective) do
        for name, obj in pairs(list) do
          if obj.pos then
            for i, cpos in pairs(obj.pos) do
              JRoutes_ConvertCoordsFromWrath(cpos)
            end
          end
        end
      end
    end
  end

  self:ResetPathing()
  
  -- Adding JRoutes_CharVersion, so I know if I've already converted this characters saved data.
  if not JRoutes_CharVersion then
    -- Changing per-character flight routes, now only storing the flight points they have,
    -- will attempt to guess the routes from this.
    local routes = {}

    for i, l in pairs(JRoutes_KnownFlightRoutes) do
      for key in pairs(l) do
        routes[key] = true
      end
    end

    JRoutes_KnownFlightRoutes = routes

    -- Deleting the player's home again.
    -- But using the new CharVersion variable I'm adding is cleaner that what I was doing, so I'll go with it.
    JRoutes_Home = nil
    JRoutes_CharVersion = 1
  end

  if not JRoutes_Home then
    -- Not going to bother complaining about the player's home not being set, uncomment this when the home is used in routing.
    -- self:TextOut(QHText("HOME_NOT_KNOWN"))
  end

  self.minimap_dodad = self:CreateMipmapDodad()

  if JRoutes_Pref.map_button then
      JRoutes:InitMapButton()
  end

  if JRoutes_Pref.cart_wp then
    self:EnableCartographer()
  end

  if JRoutes_Pref.tomtom_wp then
    self:EnableTomTom()
  end

  self.tracker:SetScale(JRoutes_Pref.track_scale)

  if JRoutes_Pref.track and not QuestHelper_Pref.hide then
    self:ShowTracker()
  end

  local version = GetAddOnMetadata("QuestHelper", "Version") or "Unknown"
  if QuestHelper_Version ~= version then
    QuestHelper_Version = version
    self:ChangeLog()
  end

  self:SetScript("OnUpdate", self.OnUpdate)

  collectgarbage("collect") -- Free everything we aren't using.

  if self.debug_objectives then
    for name, data in pairs(self.debug_objectives) do
      self:LoadDebugObjective(name, data)
    end
  end

  self.Routing:Initialize()       -- Set up the routing task
end

function JRoutes:OnEvent(event)
  if event == "VARIABLES_LOADED" then
    self:Initialize()
  end

  if event == "GOSSIP_SHOW" then
    local name, id = UnitName("npc"), self:GetUnitID("npc")
    if name and id then
      self:GetObjective("monster", name).o.id = id
      --self:TextOut("NPC: "..name.." = "..id)
    end
  end

  if event == "PLAYER_TARGET_CHANGED" then
    local name, id = UnitName("target"), self:GetUnitID("target")
    if name and id then
      self:GetObjective("monster", name).o.id = id
      --self:TextOut("Target: "..name.." = "..id)
    end

    if UnitExists("target") and UnitIsVisible("target") and UnitCreatureType("target") ~= "Critter" and not UnitIsPlayer("target") and not UnitPlayerControlled("target") then
      local index, x, y = self:UnitPosition("target")

      if index then -- Might not have a position if inside an instance.
        local w = 0.1

        -- Modify the weight based on how far they are from us.
        -- We don't know the exact location (using our own location), so the farther, the less sure we are that it's correct.
        if CheckInteractDistance("target", 3) then w = 1
        elseif CheckInteractDistance("target", 2) then w = 0.89
        elseif CheckInteractDistance("target", 1) or CheckInteractDistance("target", 4) then w = 0.33 end

        local monster_objective = self:GetObjective("monster", UnitName("target"))
        self:AppendObjectivePosition(monster_objective, index, x, y, w)

        monster_objective.o.faction = (UnitFactionGroup("target") == "Alliance" and 1) or
                                      (UnitFactionGroup("target") == "Horde" and 2) or nil

        local level = UnitLevel("target")
        if level and level >= 1 then
          local w = monster_objective.o.levelw or 0
          monster_objective.o.level = ((monster_objective.o.level or 0)*w+level)/(w+1)
          monster_objective.o.levelw = w+1
        end
      end
    end
  end

  if event == "LOOT_OPENED" then
    local target = UnitName("target")
    if target and UnitIsDead("target") and UnitCreatureType("target") ~= "Critter" and not UnitIsPlayer("target") and not UnitPlayerControlled("target") then
      local index, x, y = self:UnitPosition("target")

      local monster_objective = self:GetObjective("monster", target)
      monster_objective.o.looted = (monster_objective.o.looted or 0) + 1

      if index then -- Might not have a position if inside an instance.
        self:AppendObjectivePosition(monster_objective, index, x, y)
      end

      for i = 1, GetNumLootItems() do
        local icon, name, number, rarity = GetLootSlotInfo(i)
        if name then
          if number and number >= 1 then
            self:AppendItemObjectiveDrop(self:GetObjective("item", name), name, target, number)
          else
            local total = (name:match(COPPER_AMOUNT:gsub("%%d", "%(%%d+%)")) or 0) +
                          (name:match(SILVER_AMOUNT:gsub("%%d", "%(%%d+%)")) or 0) * 100 +
                          (name:match(GOLD_AMOUNT:gsub("%%d", "%(%%d+%)")) or 0) * 10000

            if total > 0 then
              self:AppendObjectiveDrop(self:GetObjective("item", "money"), target, total)
            end
          end
        end
      end
    else
      local container = nil

      -- Go through the players inventory and look for a locked item, we're probably looting it.
      for bag = 0,NUM_BAG_SLOTS do
        for slot = 1,GetContainerNumSlots(bag) do
          local link = GetContainerItemLink(bag, slot)
          if link and select(3, GetContainerItemInfo(bag, slot)) then
            if container == nil then
              -- Found a locked item and haven't previously assigned to container, assign its name, or false if we fail to parse it.
              container = select(3, string.find(link, "|h%[(.+)%]|h|r")) or false
            else
              -- Already tried to assign to a container. If there are multiple locked items, we give up.
              container = false
            end
          end
        end
      end

      if container then
        local container_objective = self:GetObjective("item", container)
        container_objective.o.opened = (container_objective.o.opened or 0) + 1

        for i = 1, GetNumLootItems() do
          local icon, name, number, rarity = GetLootSlotInfo(i)
          if name and number >= 1 then
            self:AppendItemObjectiveContainer(self:GetObjective("item", name), container, number)
          end
        end
      else
        -- No idea where the items came from.
        local index, x, y = self:PlayerPosition()

        if index then
          for i = 1, GetNumLootItems() do
            local icon, name, number, rarity = GetLootSlotInfo(i)
            if name and number >= 1 then
              self:AppendItemObjectivePosition(self:GetObjective("item", name), name, index, x, y)
            end
          end
        end
      end
    end
  end

  if event == "CHAT_MSG_SYSTEM" then
    local home_name = self:convertPattern(ERR_DEATHBIND_SUCCESS_S)(arg1)
    if home_name then
      if self.i then
        self:TextOut(QHText("HOME_CHANGED"))
        self:TextOut(QHText("WILL_RESET_PATH"))

        local home = QuestHelper_Home
        if not home then
          home = {}
          QuestHelper_Home = home
        end

        home[1], home[2], home[3], home[4] = self.i, self.x, self.y, home_name
        self.defered_graph_reset = true
      end
    end
  end

  if event == "CHAT_MSG_ADDON" then
    if arg1 == "QHpr" and (arg3 == "PARTY" or arg3 == "WHISPER") and arg4 ~= UnitName("player") then
      self:HandleRemoteData(arg2, arg4)
    end
  end

  if event == "PARTY_MEMBERS_CHANGED" then
    self:HandlePartyChange()
  end

  if event == "QUEST_LOG_UPDATE" or
     event == "PLAYER_LEVEL_UP" or
     event == "PARTY_MEMBERS_CHANGED" then
    self.defered_quest_scan = true
  end

  if event == "QUEST_DETAIL" then
    if not self.quest_giver then self.quest_giver = {} end
    local npc = UnitName("npc")
    if npc then
      -- Some NPCs aren't actually creatures, and so their positions might not be marked by PLAYER_TARGET_CHANGED.
      local index, x, y = self:UnitPosition("npc")

      if index then -- Might not have a position if inside an instance.
        local npc_objective = self:GetObjective("monster", npc)
        self:AppendObjectivePosition(npc_objective, index, x, y)
        self.quest_giver[GetTitleText()] = npc
      end
    end
  end

  if event == "QUEST_COMPLETE" or event == "QUEST_PROGRESS" then
    local quest = GetTitleText()
    if quest then
      local level, hash = self:GetQuestLevel(quest)
      if not level or level < 1 then
        --self:TextOut("Don't know quest level for ".. quest.."!")
        return
      end
      local q = self:GetQuest(quest, level, hash)

      if q.need_hash then
        q.o.hash = hash
      end

      local unit = UnitName("npc")
      if unit then
        q.o.finish = unit
        q.o.pos = nil

        -- Some NPCs aren't actually creatures, and so their positions might not be marked by PLAYER_TARGET_CHANGED.
        local index, x, y = self:UnitPosition("npc")
        if index then -- Might not have a position if inside an instance.
          local npc_objective = self:GetObjective("monster", unit)
          self:AppendObjectivePosition(npc_objective, index, x, y)
        end
      elseif not q.o.finish then
        local index, x, y = self:PlayerPosition()
        if index then -- Might not have a position if inside an instance.
          self:AppendObjectivePosition(q, index, x, y)
        end
      end
    end
  end

  if event == "MERCHANT_SHOW" then
    local npc_name = UnitName("npc")
    if npc_name then
      local npc_objective = self:GetObjective("monster", npc_name)
      local index = 1
      while true do
        local item_name = GetMerchantItemInfo(index)
        if item_name then
          index = index + 1
          local item_objective = self:GetObjective("item", item_name)
          if not item_objective.o.vendor then
            item_objective.o.vendor = {npc_name}
          else
            local known = false
            for i, vendor in ipairs(item_objective.o.vendor) do
              if npc_name == vendor then
                known = true
                break
              end
            end
            if not known then
              table.insert(item_objective.o.vendor, npc_name)
            end
          end
        else
          break
        end
      end
    end
  end

  if event == "TAXIMAP_OPENED" then
    self:taxiMapOpened()
  end
  
  if event == "PLAYER_CONTROL_GAINED" then
    interruptcount = interruptcount + 1
  end

  if event == "BAG_UPDATE" then
    for slot = 1,GetContainerNumSlots(arg1) do
      local link = GetContainerItemLink(arg1, slot)
      if link then
        local id, name = select(3, string.find(link, "|Hitem:(%d+):.-|h%[(.-)%]|h"))
        if name then
          self:GetObjective("item", name).o.id = tonumber(id)
        end
      end
    end
  end
end

local map_shown_decay = 0
local delayed_action = 100
local update_count = 0
local ontaxi = false

function JRoutes:OnUpdate()
  
  if not ontaxi and UnitOnTaxi("player") then
    self:flightBegan()
    interruptcount = 0
  elseif ontaxi and not UnitOnTaxi("player") then
    self:flightEnded(interruptcount > 1)
  end
  ontaxi = UnitOnTaxi("player")
  
  update_count = update_count - 1

  if update_count <= 0 then

    -- Reset the update count for next time around; this will make sure the body executes every time
    -- when perf_scale >= 1, and down to 1 in 10 iterations when perf_scale < 1, or when hidden.
    update_count = update_count + (QuestHelper_Pref.hide and 10 or 1/QuestHelper_Pref.perf_scale)

    if update_count < 0 then
      -- Make sure the count doesn't go perpetually negative; don't know what will happen if it underflows.
      update_count = 0
    end

    if self.Astrolabe.WorldMapVisible then
      -- We won't trust that the zone returned by Astrolabe is correct until map_shown_decay is 0.
      map_shown_decay = 2
    elseif map_shown_decay > 0 then
      map_shown_decay = map_shown_decay - 1
    else
      SetMapToCurrentZone()
    end

    delayed_action = delayed_action - 1
    if delayed_action <= 0 then
      delayed_action = 100
      self:HandlePartyChange()
    end

    local nc, nz, nx, ny = self.Astrolabe:GetCurrentPlayerPosition()

    if nc and nc == self.c and map_shown_decay > 0 and self.z > 0 and self.z ~= nz then
      -- There's a chance Astrolable will return the wrong zone if you're messing with the world map, if you can
      -- be seen in that zone but aren't in it.
      local nnx, nny = self.Astrolabe:TranslateWorldMapPosition(nc, nz, nx, ny, nc, self.z)
      if nnx > 0 and nny > 0 and nnx < 1 and nny < 1 then
        nz, nx, ny = self.z, nnx, nny
      end
    end

    if nc and nc > 0 and nz == 0 and nc == self.c and self.z > 0 then
      nx, ny = self.Astrolabe:TranslateWorldMapPosition(nc, nz, nx, ny, nc, self.z)
      if nx and ny and nx > -0.1 and ny > -0.1 and nx < 1.1 and ny < 1.1 then
        nz = self.z
      else
        nc, nz, nx, ny = nil, nil, nil, nil
      end
    end

    if nc and nz > 0 then
      self.c, self.z, self.x, self.y = nc, nz, nx, ny
      self.i = QuestHelper_IndexLookup[nc][nz]
    end

    if self.defered_quest_scan and not self.graph_in_limbo then
      self.defered_quest_scan = false
      self:ScanQuestLog()
    end

    if self.c then
      self:RunCoroutine()
    end

    local level = UnitLevel("player")
    if level >= 58 and self.player_level < 58 then
      self.defered_graph_reset = true
    end
    self.player_level = level

    self:PumpCommMessages()
  end
end

JRoutes:RegisterEvent("VARIABLES_LOADED")
JRoutes:SetScript("OnEvent", JRoutes.OnEvent)
